package com.syni.mdd.sjb.common.component.utils.common.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 由于 时间戳 并不能直接被 fastJSON 转换为 LocalDateTime 类型，因此我们需要自定义一个序列化执行器
 * LocalDateTime 反序列化（将前端传递的 时间戳 转换为 LocalDateTime 类型）
 *
 * @author Chimm Huang
 * @date 2020/3/7
 */
public class CoustemLocalDateTimeDeserializer extends LocalDateTimeDeserializer {

    public CoustemLocalDateTimeDeserializer(){
        super(DateTimeFormatter.ofPattern(DateTimeUtils.DATE_PATTERN_TIMESTAMP));

    }


    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        String timestampStr = parser.getValueAsString();

        if (StringUtils.isBlank(timestampStr)) {
            return null;
        }

        timestampStr = timestampStr.replaceAll("\"", "");

        long timestamp = Long.parseLong(timestampStr);
        if(timestamp == 0) {
            return null;
        }
        return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
    }
}

